package com.example.lilin.httpdemo;

import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class MainActivity extends Activity {

    public static final int SHOW_RESPONSE_SUCCESS   = 1;
    public static final int SHOW_RESPONSE_FAIL      = 2;

    @BindView(R.id.send_request1)
    Button getRequestButton;
    @BindView(R.id.formatButton)
    Button formatJsonButton;
    @BindView(R.id.response_text)
    TextView showText;

    public static String responseStr;

    private Handler handler = new Handler() {
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case SHOW_RESPONSE_SUCCESS:
                    // Toast.makeText(MainActivity.this, "请求成功!", Toast.LENGTH_SHORT).show();
                    String response = (String) msg.obj;
                    showText.setText(response);
                    break;
                case SHOW_RESPONSE_FAIL:
                    showText.setText("请求失败!");
                    break;
                default:
                    break;
            }
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        ButterKnife.bind(this);
    }

    // 发送HttpURLConnection请求:GET
    private void sendRequestWithHttpURLConnection() {
        // 开启线程来发起网络请求
        new Thread(new Runnable() {
            @Override
            public void run() {
                HttpURLConnection connection = null;
                try {
                    URL url = new URL("http://218.4.136.118:8086/mockjs/286/login");
                    connection = (HttpURLConnection) url.openConnection();
                    connection.setRequestMethod("GET"); // GET请求（默认）
                    connection.setConnectTimeout(8000); // 设置 链接 超时时间
                    connection.setReadTimeout(8000);    // 设置 读取 超时时间
                    connection.setDoInput(true);        // 设置是否从HttpURLConnection读入，默认为true
                    connection.setDoOutput(true);

                    if (connection.getResponseCode() == HttpURLConnection.HTTP_OK) { // 请求相应码是否为200（OK）
                        // 下面对获取到的输入流进行读取
                        InputStream in          = connection.getInputStream();
                        BufferedReader reader   = new BufferedReader(new InputStreamReader(in));
                        StringBuilder response  = new StringBuilder();
                        String line;
                        while ((line = reader.readLine()) != null) {
                            response.append(line);
                        }
                        responseStr = response.toString();

                        Message message = new Message();
                        message.what    = SHOW_RESPONSE_SUCCESS;
                        message.obj     = response.toString();
                        handler.sendMessage(message);
                    } else {
                        Message message = new Message();
                        message.what    = SHOW_RESPONSE_FAIL;
                        handler.sendMessage(message);
                    }

                } catch (Exception e) {
                    e.printStackTrace();
                } finally {
                    // 关闭连接
                    if (connection != null) {
                        connection.disconnect();
                    }
                }
            }
        }).start();
    }

    /** 格式化JSON **/
    public static String stringToJSON(String strJson) {
        // 计数tab的个数
        int tabNum = 0;
        StringBuffer jsonFormat = new StringBuffer();
        int length = strJson.length();

        char last = 0;
        for (int i = 0; i < length; i++) {
            char c = strJson.charAt(i);
            if (c == '{') {
                tabNum++;
                jsonFormat.append(c + "\n");
                jsonFormat.append(getSpaceOrTab(tabNum));
            } else if (c == '}') {
                tabNum--;
                jsonFormat.append("\n");
                jsonFormat.append(getSpaceOrTab(tabNum));
                jsonFormat.append(c);
            } else if (c == ',') {
                jsonFormat.append(c + "\n");
                jsonFormat.append(getSpaceOrTab(tabNum));
            } else if (c == ':') {
                jsonFormat.append(c + " ");
            } else if (c == '[') {
                tabNum++;
                char next = strJson.charAt(i + 1);
                if (next == ']') {
                    jsonFormat.append(c);
                } else {
                    jsonFormat.append(c + "\n");
                    jsonFormat.append(getSpaceOrTab(tabNum));
                }
            } else if (c == ']') {
                tabNum--;
                if (last == '[') {
                    jsonFormat.append(c);
                } else {
                    jsonFormat.append("\n" + getSpaceOrTab(tabNum) + c);
                }
            } else {
                jsonFormat.append(c);
            }
            last = c;
        }
        return jsonFormat.toString();
    }

    private static String getSpaceOrTab(int tabNum) {
        StringBuffer sbTab = new StringBuffer();
        for (int i = 0; i < tabNum; i++) {
            sbTab.append('\t');
        }
        return sbTab.toString();
    }

    @OnClick({R.id.send_request1, R.id.formatButton})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.send_request1:
                showText.setText("");
                sendRequestWithHttpURLConnection();
                break;
            case R.id.formatButton:
                if (responseStr != null) {
                    showText.setText(stringToJSON(responseStr));
                } else {
                    Toast.makeText(this, "请发起HTTP请求！", Toast.LENGTH_SHORT).show();
                }
                break;
        }
    }
}
